package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@WebFilter(filterName = "loginCheckFilter")
public class LoginCheckFilter implements Filter{

    // 授权的URL
    private String[] authUrl = new String[]{
            "/backend/**",
            "/front/**",
            "/employee/login",
            "/employee/logout",
            "/common/**",
            "/user/sendMsg",  //移动端的发送短信
            "/user/login"   //移动端登录
    };


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //拦截所有请求，包括了静态和动态的资源     //过滤器的处理逻辑
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取uri
        String uri = request.getRequestURI();
        log.info("[登录检查过滤器...],当前uri:{}",uri);
        //确定哪些uri是放行 登录页面放行，静态资源
        // /backend/*,front/*
        // 登录的uri放行 /employee/login /employee/logout
        //2.判断uri是否需要处理（是否拦截）
        boolean isAuth = checkAuthUrl(uri);
        //3.如果不需要，就放行
        if (isAuth){
            //所有静态资源都放行
            log.info("[登录检查过滤器],允许放行");
            filterChain.doFilter(request,response);
            return;
        }
        //  /employee/page,这个资源需要验证是否登陆过
        //4.如果需要，判断是否登录过
        if (request.getSession().getAttribute("employee")!= null){
//            log.info("[登录检查，已登录 id:{}]",request.getSession().getAttribute("employee"));
            log.info("[登录检查过滤器],已登录，允许通过");
            Thread thread = Thread.currentThread();
            log.info("[登录检查过滤器],已登录，允许通过: 当前线程ID:{}",thread.getId());

            Long empId = (Long)request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);

            filterChain.doFilter(request,response);
            return;
        }

        // 判断移动端是否登录过（后台登录）
        if (request.getSession().getAttribute("user")!= null){
            log.info("[登录检查过滤器],移动端已登录，允许通过");
            Thread thread = Thread.currentThread();
            log.info("[登录检查过滤器],移动端已登录，允许通过: 当前线程ID:{}",thread.getId());
            Long empId = (Long)request.getSession().getAttribute("user");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request,response);
            return;
        }

        //5.如果未登录，返回未登录的错误信息
        log.info("[登录失败，未授权....]");
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
    }



    //匹配路径
    final AntPathMatcher pathMatcher = new AntPathMatcher();

    private boolean checkAuthUrl(String requestURI){
        for (String url:authUrl){
            if (pathMatcher.match(url,requestURI)){
                log.info("[登录检查过滤器],匹配放行的url:{}",url);
                return true;
            }
        }
        return false;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
